import { Global, Module } from '@nestjs/common';
import Redis from 'ioredis';

import { ConfigurationModule } from '@src/config/configuration.module';
import { ConfigurationService } from '@src/config/configuration.service';

import { RedisService } from './redis.service';

@Global()
@Module({
  imports: [ConfigurationModule],
  providers: [
    {
      provide: Redis,
      inject: [ConfigurationService],
      useFactory: (configurationService: ConfigurationService) => {
        const cfg = configurationService.app;
        return new Redis({
          host: cfg.redisHost,
          port: cfg.redisPort,
          password: cfg.redisPassword,
          db: cfg.redisDb,
          keyPrefix: cfg.redisPrefix,
          enableOfflineQueue: true,
          retryStrategy(times) {
            if (times > 20) {
              return;
            }
            const delay = Math.min(2 ** times * 10, 300);
            return times <= 5 ? delay : 1000;
          },
          maxRetriesPerRequest: 3,
          lazyConnect: true, // 第一次使用时才真正 connect
        });
      },
    },
    RedisService,
  ],
  exports: [RedisService],
})
export class RedisModule {}
